package web;

import core.AjaxResult;
import core.BaseHttpServlet;
import dao.ISignInDao;
import dao.impl.SignInDaoImpl;
import domain.SignRecord;
import service.ISignInService;
import service.impl.SignInServiceImpl;
import util.RequestUtils;
import util.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 签到，记录查询
 */
@WebServlet("/student/homepage")
public class SignInServlet extends BaseHttpServlet {
    private ISignInService signInService;

    @Override
    public void init() throws ServletException {
        signInService = new SignInServiceImpl(new SignInDaoImpl());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SignRecord signRecord = new SignRecord();
        signRecord.setStudentId(Integer.parseInt(req.getParameter("student_id")));
        signRecord.setSignTime(new Date());
        try {
            int i = signInService.addSignRecord(signRecord);
            ResponseUtils.responseJSON(resp, AjaxResult.success(i));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getLocalizedMessage());
            ResponseUtils.responseJSON(resp, AjaxResult.error(500, "签到失败，请联系管理员"));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        if (pathInfo == null) {
           SignRecord signRecord = RequestUtils.getReqJsonBody(req, SignRecord.class);
            executeBusiness(resp,response -> {
                ResponseUtils.responseJSON(resp, AjaxResult.success(signInService.selectSignRecord(signRecord)));
            });
        }
    }
}
